package admin

import (
	"crypto/md5"
	"encoding/hex"
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/spf13/cast"
	"outsourced-projects/pkg/communal"
	"outsourced-projects/service"
	"strings"
	"time"
)

type Administrators struct {
	service.Base
}

func (administrators Administrators) List(c *gin.Context) {
	var err error
	//数据获取
	jsondata := make(map[string]interface{})
	err = c.BindJSON(&jsondata)
	if err != nil {
		service.ReturnJson(c, 500, err.Error(), gin.H{})
		return
	}

	//初始化数据库
	db := communal.Sql()
	defer db.Close()

	limitstr := fmt.Sprintf(" limit %d,%d", (cast.ToInt(jsondata["page_index"])-1)*cast.ToInt(jsondata["page_size"]), cast.ToInt(jsondata["page_size"]))
	orderstr := " order by ctime desc"

	wheresql := strings.Builder{}
	//wheresql.WriteString(fmt.Sprintf(" and a.status = 0"))
	if cast.ToString(jsondata["nickname"]) != "" {
		wheresql.WriteString(fmt.Sprintf(" and a.`nickname` like '%s'", "%"+cast.ToString(jsondata["nickname"])+"%"))
	}

	listsql := fmt.Sprintf("select a.`id`,a.`nickname`,a.`status`,a.`account`,FROM_UNIXTIME(a.`ctime`) as ctime,a.`notes` from `admin` as a where 1=1 %s %s %s", wheresql.String(), orderstr, limitstr)
	listdata, err := db.QueryString(listsql)
	if err != nil {
		service.ReturnJson(c, 500, err.Error(), gin.H{})
		return
	}

	countsql := fmt.Sprintf("select count(*) as total from `admin` as a where 1=1 %s", wheresql.String())
	countdata, err := db.QueryString(countsql)
	if err != nil {
		service.ReturnJson(c, 500, err.Error(), gin.H{})
		return
	}

	service.ReturnJson(c, 200, "获取成功", gin.H{
		"list":  listdata,
		"total": cast.ToInt(countdata[0]["total"]),
	})
}

func (administrators Administrators) Insert(c *gin.Context) {
	var err error
	//数据获取
	jsondata := make(map[string]interface{})
	err = c.BindJSON(&jsondata)
	if err != nil {
		service.ReturnJson(c, 500, err.Error(), gin.H{})
		return
	}

	userid, ok := c.Get("userid")
	if !ok {
		service.ReturnJson(c, 500, errors.New("userid获取失败").Error(), gin.H{})
		return
	}

	//初始化数据库
	db := communal.Sql()
	defer db.Close()

	if cast.ToInt(userid) != 1 {
		service.ReturnJson(c, 500, errors.New("当前账号不允许操作").Error(), gin.H{})
		return
	}

	d := []byte(fmt.Sprintf("vR8OS%s", jsondata["password"]))
	m := md5.New()
	m.Write(d)
	passwordStr := hex.EncodeToString(m.Sum(nil))

	inserdata := make(map[string]interface{})
	inserdata["nickname"] = cast.ToString(jsondata["nickname"])
	inserdata["account"] = cast.ToString(jsondata["account"])
	inserdata["password"] = passwordStr
	inserdata["notes"] = cast.ToString(jsondata["notes"])
	inserdata["ctime"] = time.Now().Unix()
	inserdata["utime"] = time.Now().Unix()

	_, err = db.Table("admin").Insert(inserdata)
	if err != nil {
		service.ReturnJson(c, 500, err.Error(), gin.H{})
		return
	}

	service.ReturnJson(c, 200, "操作成功", gin.H{})
}

func (administrators Administrators) Save(c *gin.Context) {
	var err error
	//数据获取
	jsondata := make(map[string]interface{})
	err = c.BindJSON(&jsondata)
	if err != nil {
		service.ReturnJson(c, 500, err.Error(), gin.H{})
		return
	}

	userid, ok := c.Get("userid")
	if !ok {
		service.ReturnJson(c, 500, errors.New("userid获取失败").Error(), gin.H{})
		return
	}

	if cast.ToInt(userid) != 1 {
		service.ReturnJson(c, 500, errors.New("当前账号不允许操作").Error(), gin.H{})
		return
	}

	//初始化数据库
	db := communal.Sql()
	defer db.Close()

	updatedata := make(map[string]interface{})
	updatedata["nickname"] = cast.ToString(jsondata["nickname"])
	updatedata["account"] = cast.ToString(jsondata["account"])
	updatedata["notes"] = cast.ToString(jsondata["notes"])
	updatedata["utime"] = time.Now().Unix()

	_, err = db.Table("admin").Where("id = ?", cast.ToInt(jsondata["id"])).Cols("nickname", "account", "notes", "utime").Update(updatedata)
	if err != nil {
		service.ReturnJson(c, 500, err.Error(), gin.H{})
		return
	}

	service.ReturnJson(c, 200, "操作成功", gin.H{})
}

func (administrators Administrators) SavePasswd(c *gin.Context) {
	var err error
	//数据获取
	jsondata := make(map[string]interface{})
	err = c.BindJSON(&jsondata)
	if err != nil {
		service.ReturnJson(c, 500, err.Error(), gin.H{})
		return
	}

	userid, ok := c.Get("userid")
	if !ok {
		service.ReturnJson(c, 500, errors.New("userid获取失败").Error(), gin.H{})
		return
	}

	if cast.ToInt(userid) != 1 {
		service.ReturnJson(c, 500, errors.New("当前账号不允许操作").Error(), gin.H{})
		return
	}

	//初始化数据库
	db := communal.Sql()
	defer db.Close()

	oldm := md5.New()
	oldm.Write([]byte(fmt.Sprintf("vR8OS%s", jsondata["old_password"])))
	oldPasswordStr := hex.EncodeToString(oldm.Sum(nil))

	user, err := db.QueryString(fmt.Sprintf("select * from `admin` where `id` = %d and `password` = '%s'", cast.ToInt(jsondata["id"]), oldPasswordStr))
	if err != nil {
		service.ReturnJson(c, 500, err.Error(), gin.H{})
		return
	}
	if len(user) <= 0 {
		service.ReturnJson(c, 500, errors.New("原始密码错误").Error(), gin.H{})
		return
	}

	newm := md5.New()
	newm.Write([]byte(fmt.Sprintf("vR8OS%s", jsondata["new_password"])))
	newPasswordStr := hex.EncodeToString(newm.Sum(nil))

	updatedata := make(map[string]interface{})
	updatedata["password"] = newPasswordStr
	updatedata["utime"] = time.Now().Unix()

	_, err = db.Table("admin").Where("id = ?", cast.ToInt(jsondata["id"])).Cols("password", "utime").Update(updatedata)
	if err != nil {
		service.ReturnJson(c, 500, err.Error(), gin.H{})
		return
	}

	service.ReturnJson(c, 200, "操作成功", gin.H{})
}

func (administrators Administrators) Del(c *gin.Context) {
	var err error
	//数据获取
	jsondata := make(map[string]interface{})
	err = c.BindJSON(&jsondata)
	if err != nil {
		service.ReturnJson(c, 500, err.Error(), gin.H{})
		return
	}

	userid, ok := c.Get("userid")
	if !ok {
		service.ReturnJson(c, 500, errors.New("userid获取失败").Error(), gin.H{})
		return
	}

	if cast.ToInt(userid) != 1 {
		service.ReturnJson(c, 500, errors.New("当前账号不允许操作").Error(), gin.H{})
		return
	}

	//初始化数据库
	db := communal.Sql()
	defer db.Close()

	updatedata := make(map[string]interface{})
	updatedata["status"] = cast.ToInt(jsondata["status"])
	updatedata["utime"] = time.Now().Unix()

	_, err = db.Table("admin").Where("id = ?", cast.ToInt(jsondata["id"])).Cols("status", "utime").Update(updatedata)
	if err != nil {
		service.ReturnJson(c, 500, err.Error(), gin.H{})
		return
	}

	service.ReturnJson(c, 200, "操作成功", gin.H{})
}
